package com.heima.media.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.MediaThreadLocalUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    // 前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取用户id
        String userId = request.getHeader("userId");
        if (!StringUtils.isEmpty(userId)) {
            // 将用户id存放到ThreadLocal中
            User user = new User();
            user.setUserId(Integer.parseInt(userId));
            MediaThreadLocalUtil.set(user);
        }
        // 不管有没有userId,都放行(后续有一些操作可以允许用户不需要登录,比如APP端查看文章)
        return true;
    }

    // 后置拦截 已经处理后给前端响应,这个时候拦截可以修改响应内容
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        MediaThreadLocalUtil.remove();
    }
}
